# == Schema Information
# Schema version: 38
#
# Table name: groups
#
#  id           :integer(11)     not null, primary key
#  creator_id   :integer(11)
#  title        :string(255)
#  content      :text
#  content_html :text
#  created_at   :datetime
#  updated_at   :datetime
#

class Group < ActiveRecord::Base
  validates_presence_of :title
  validates_uniqueness_of :title, :case_sensitive => false

  format_attribute :content
  
  # when a user create a group, he become the moderator & member of this group automatically
  #
  # need factor? add an observer to handle after_create, strip other models out of Group
  after_create {|g| Moderatorship.create(:group_id => g.id, :user_id => g.creator_id)}
  after_create {|g| GroupMembership.create(:group_id => g.id, :user_id => g.creator_id)}
  
  belongs_to :creator, :class_name => "User", :foreign_key => "creator_id"
  has_many :topics, :order => "sticky desc, replied_at desc", :dependent => :delete_all
  
  has_many :group_memberships, :dependent => :delete_all
  has_many :members, :through => :group_memberships, :source => :user
  
  has_many :moderatorships, :dependent => :delete_all
  has_many :moderators, :through => :moderatorships, :source => :user
  
  
  def editable_by?(user)
    user!=:false && (user.id == creator_id || user.is_admin? || moderated_by?(user))
  end
  
  def moderated_by?(user)
    user!=:false && moderatorships.count("#{Moderatorship.table_name}.id", 
                                          :conditions => ["user_id=?", (user.is_a?(User) ? user.id : user)])>0
  end
  
  def has_member?(user)
    user!=:false && group_memberships.count("#{GroupMembership.table_name}.id", 
                                            :conditions => ["user_id=?", (user.is_a?(User) ? user.id : user)])>0
  end
  
  protected

end
